package com.kunlun.center.config;

import com.alibaba.fastjson.JSONObject;
import com.kunlun.common.utils.AMQPUtil;
import com.netflix.appinfo.InstanceInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Locale;

@Configuration
public class ServiceStateListener {

    private Logger log = LogManager.getLogger();

    @Value("${spring.application.name}")
    private String name;
    @Autowired
    private AMQPUtil amqpUtil;

    @EventListener
    public void registerListen(EurekaInstanceRegisteredEvent registeredEvent) {
        InstanceInfo instanceInfo = registeredEvent.getInstanceInfo();
        String serviceName = instanceInfo.getAppName().toLowerCase(Locale.ROOT);
        log.info("ServiceStateConfig registerListen instanceInfo => " + JSONObject.toJSONString(instanceInfo));
        if (ObjectUtils.isEmpty(instanceInfo.getActionType()) || serviceName.equals(name) ||
                !ObjectUtils.isEmpty(instanceInfo.getActionType()) && !instanceInfo.getActionType().equals(InstanceInfo.ActionType.ADDED)) {
            return;
        }
        int second = LocalDateTime.now().getSecond();
        while (true) {
            if (LocalDateTime.now().getSecond() > (second + 20)) {
                break;
            }
        }
        log.info("ServiceStateConfig registerListen send finish!");
        amqpUtil.sendMessage(JSONObject.toJSONString(instanceInfo));
    }

    @EventListener
    public void offlineListen(EurekaInstanceCanceledEvent registeredEvent) {
        String serviceName = registeredEvent.getAppName().toLowerCase(Locale.ROOT);
        log.info("ServiceStateConfig offlineListen instanceInfo => " + JSONObject.toJSONString(registeredEvent));
        int second = LocalDateTime.now().getSecond();
        while (true) {
            if (LocalDateTime.now().getSecond() > (second + 20)) {
                break;
            }
        }
        log.info("ServiceStateConfig offlineListen send finish!");
        amqpUtil.sendMessage(JSONObject.toJSONString(registeredEvent));
    }
}
